'''
Created on Jul 21, 2009

@author: cvirus
'''

import sys

from PyQt4.QtSql import QSqlDatabase, QSqlQuery, QSqlError, QSqlTableModel

class Configurator(object):
    '''
    A Configurator class used for configuring an existing schema or creating a
    new one from scratch.
    '''
    databaseDriver = None
    databaseConnectionName = None
    databaseName = None
    databaseHost = None
    databaseUsername = None
    databasePassword = None


    def __init__(self, databaseDriver='QMYSQL', databaseConnectionName=None, databaseName='lickit', databaseHost='localhost', databaseUsername='root', databasePassword='hellothere'):
        '''
        TODO: Fix docs.

        Configurator constructor.
        Defaults to QMYSQL driver, default connection name provided by Qt,
        default "lickit" database, default database host localhost, 
        '''
        self.databaseDriver = databaseDriver
        self.databaseConnectionName = databaseConnectionName
        self.databaseName = databaseName
        self.databaseHost = databaseHost
        self.databaseUsername = databaseUsername
        self.databasePassword = databasePassword

        if self.databaseConnectionName == None:
            db = QSqlDatabase.addDatabase(self.databaseDriver)
        else:
            db = QSqlDatabase.addDatabase(self.databaseDriver, self.databaseConnectionName)

        db.setDatabaseName(self.databaseName)
        db.setHostName(self.databaseHost)
        db.setUserName(self.databaseUsername)
        db.setPassword(self.databasePassword)

        if not db.open():
            print "Failed to open Database"
        else:
            print "Database opened"

    def createSchema(self, schemaName):
        '''
        TODO: Plain configuration files support.

        Method used to create a new schema named schemaName.
        A Schema is simply a database table(for now at least ?)
        '''
        createSchemaQuery = QSqlQuery("CREATE TABLE " + schemaName + "(node VARCHAR(50) NOT NULL,  PRIMARY KEY(node),  value TEXT)")

        if createSchemaQuery.lastError().type() != 0:
            print "Database error has occured: " + str(createSchemaQuery.lastError().type())
            print "Error: " + createSchemaQuery.lastError().text()
        else:
            print "Query executed Successfully"

    def insertSchemaRecord(self, shemaName, node, value):
        '''
        TODO: Method implementation
        '''
        pass

    def getSchema(self, schemaName):
        '''
        Returns a dictionary mapping of the given Schema.
        Node -> Value
        '''
        schemaDictionary = {}

        self.schemaModel = QSqlTableModel()
        self.schemaModel.setTable(schemaName)
        self.schemaModel.select()

        i = 0
        while i < self.schemaModel.rowCount():
            schemaDictionary[str(self.schemaModel.record(i).value("node").toString())] = str(self.schemaModel.record(i).value("value").toString())
            i = i + 1

        return schemaDictionary

    def dumpSchemaToStandardOutput(self, schemaName):
        '''
        Dumps the given schema to the standard output.
        '''
        schemaDictionary = self.getSchema(schemaName)

        for node, value in schemaDictionary.iteritems():
            print node + "=" + '''"''' + value + '''"'''

    def dumpSchemaToFile(self, schemaName, filePath):
        '''
        TODO:

        Dumps the given schema to a file that has the exact name as schemaName.
        filePath is the path where to save the file.
        '''
        schemaDictionary = self.getSchema(schemaName)

        f = open(filePath + schemaName, 'w')
        
        for node, value in schemaDictionary.iteritems():
            f.write(node + "=" + '''"''' + value + '''"''' + '\n')
